package sk.mka.phd.timit.storage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import sk.mka.utils.files.writer.BufferFileWriter;
import sk.mka.utils.tools.filesystem.DirectoryUtils;

/**
 *
 * @author katrami
 * @date Aug 25, 2010
 */
public class PhonemeStorage implements IPhonemeStorage {

    public static boolean showedStorageDimension = false;
    private final static Logger log = Logger.getLogger(PhonemeStorage.class);
    private static HashMap<Integer, ArrayList> inputHashMap = new HashMap<Integer, ArrayList>();
    private static HashMap<Integer, BufferedWriter> inputHashMapFiles = new HashMap<Integer, BufferedWriter>();
    private static int storageSize;
    private static IPhonemeStorage singletonObject;
    // Note  the constructor is private


//    private PhonemeStorageSingleton() {
//        // Optional Code
//    }
//    public static synchronized IPhonemeStorage getInstance(int colsMaxLength, final String outputFolder) {
//        if (singletonObject == null) {
//            singletonObject = new PhonemeStorageSingleton();
//            storageSize = colsMaxLength;
//            //  initialize(outputFolder, colsMaxLength);
//        }
//
//        return singletonObject;
//    }

    @Override
    public void initialize(final String outputFolder, int size) {

        prepareOutputFolder(outputFolder);

        for (int i = 0; i < size; i++) {
            inputHashMap.put(i, new ArrayList());
        }
        BufferedWriter writer;
        for (int i = 0; i < size; i++) {
            String finalNewOutputName = outputFolder + "/" + i + ".csv";
            log.debug(finalNewOutputName);
            try {
                writer = BufferFileWriter.openFileForWriting(finalNewOutputName, true);
                inputHashMapFiles.put(i, writer);
            } catch (IOException ex) {
                log.error(ex);
            }
        }
    }

    @Override
    public void closeOutputFiles() {
        for (int i = 0; i < storageSize; i++) {
            try {
                BufferedWriter outputFile = inputHashMapFiles.get(i);
                outputFile.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(PhonemeStorage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static void prepareOutputFolder(String output) {
        DirectoryUtils.removeDirectory(new File(output));
        DirectoryUtils.createDirectory(output);
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    @Override
    public void saveToFile(Integer winnerId, ArrayList line) {
        try {
            BufferedWriter outputFile = inputHashMapFiles.get(winnerId);
            for (int j = 0; j < line.size(); j++) {
                try {
                    outputFile.append(line.get(j).toString());
                    if (j != line.size() - 1) {
                        outputFile.append(",");
                    }
                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(PhonemeStorage.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            outputFile.append("\n");

        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(PhonemeStorage.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Override
    public final void saveStorage(final String outputFolder) {

        DirectoryUtils.removeDirectory(new File(outputFolder));
        DirectoryUtils.createDirectory(outputFolder);
        BufferedWriter outputFile;

        for (int i = 0; i < storageSize; i++) {
            ArrayList x = inputHashMap.get(i);
            if (x.size() > 0) {
                try {
                    String finalNewOutputName = outputFolder + "/" + i + ".csv";
                    log.debug(finalNewOutputName);
                    outputFile = BufferFileWriter.openFileForWriting(finalNewOutputName, true);
                    saveStorageToFile(outputFile, x);
                    outputFile.close();
                } catch (IOException ex) {
                    log.error(ex);
                }

            }
        }
    }

    @Override
    public void saveInput(Integer winnerId, ArrayList cols) {
        inputHashMap.get(winnerId).add(cols);
    }

    private void saveStorageToFile(BufferedWriter outputFile, ArrayList x) {

        for (int i = 0; i < x.size(); i++) {
            try {
                ArrayList line = (ArrayList) x.get(i);
                for (int j = 0; j < line.size(); j++) {
                    outputFile.append(line.get(j).toString());
                    if (j != line.size() - 1) {
                        outputFile.append(",");
                    }
                }
                outputFile.append("\n");

            } catch (IOException ex) {
                log.error(ex);
            }
        }
    }
}
